package utils;
import common.ClientEntity;

public class ServerMessage 
{

		public static final String MESSAGE_DELIMITER = ClientServerMessage.MESSAGE_DELIMITER;
		public static final String MESSAGE_DELIMITER_SHORT = ClientServerMessage.MESSAGE_DELIMITER_SHORT;
		
		protected ClientServerEnum messageType;
		protected String [] messageData;
		protected String msgData1;
		protected String msgData2;
		
		
		public ServerMessage(ClientServerEnum msgType, String msgData1, String msgData2)
		{	
			this.messageType = msgType;
			this.msgData1 = msgData1;
			this.msgData2 = msgData2;
		}
		
		public ServerMessage(String msg) 
		{
			this.SplitMsg(msg);
		}
		private void SplitMsg(String msg)
		{
			String [] msgSplit = msg.split(MESSAGE_DELIMITER);
			this.messageType = ClientServerEnum.ConvertFromInt(Integer.parseInt(msgSplit[0]));
			if(msgSplit.length > 1)
			{
				this.messageData = msgSplit[1].split(MESSAGE_DELIMITER_SHORT);
			}
			if(this.messageType == ClientServerEnum.SERVER_2_SERVER_HEARTBEAT)
			{
				this.msgData1 = this.messageData[0];
			}
			
		}
		public ServerMessage(byte[] input)
		{
			String msg = new String(input, 0, input.length);
			this.SplitMsg(msg);
		}
		
		public static String GenerateACKChecksum(byte[] input)
		{
			return ClientServerEnum.SERVER_2_SERVER_HEARTBEAT.ordinal() + MESSAGE_DELIMITER + Hashes.CheckSum(input);
		}
		public boolean IsServerAck()
		{
			if(this.messageType == ClientServerEnum.SERVER_2_SERVER_HEARTBEAT)
				return true;
			return false;
		}
		
		public long getChecksum()
		{
			return Long.parseLong(this.msgData1.trim());
		}
		
		public int getClientID()
		{
			return Integer.parseInt(this.messageData[0].trim());
		}
		
		public String getClientContent()
		{
			return this.messageData[1];
		}
		
		public String getServerMessage()
		{
			return messageType.ordinal() + MESSAGE_DELIMITER+ this.msgData1+MESSAGE_DELIMITER_SHORT + this.msgData2 + "\n";
		}
		
	}
